#include "trace.h"

using namespace Downloader::Trace;

dtrace g_dtrace;

// dtrace 构造
dtrace::dtrace():level(DTRACE_DEFAULT_LVL)
{
	if (DTRACE_DEFAULT_OUT == DTRACE_OUT_STAND) {
		stream = stdout;
	} else {
		stream = fopen(DTRACE_DEFAULT_NAME, "w+");
	}
}

// 判断日志等级
bool dtrace::lvl_check(int lvl)
{
	if (lvl < level) {
		return false;
	}
	return true;
}

// 获取日志输出流
FILE *dtrace::stream_get(dtrace& dtrace)
{
	return this->stream;
}

// dtrace 析构
dtrace::~dtrace()
{
	if (DTRACE_DEFAULT_OUT == DTRACE_OUT_FILE) {
		if (stream) {fflush(stream);fclose(stream);stream = NULL;}
	}
}

// 日志输出
void Downloader::Trace::trace(int lvl, const char *func, const char *fmt, ...)
{
	FILE *fp;
	va_list args;
	struct tm *tm;
	time_t rawtime = time(NULL);

	if (!g_dtrace.lvl_check(lvl)) {
		return;
	}

	tm = localtime(&rawtime);

	fp = g_dtrace.stream_get(g_dtrace);
	va_start(args, fmt);
	fprintf(fp, "[%04d-%02d-%02d %02d:%02d:%02d][%3s] %24s |",
			(tm->tm_year+1900), tm->tm_mon, tm->tm_mday,
			tm->tm_hour, tm->tm_min, tm->tm_sec, g_dtrace.lvl_str[lvl], func);
	vfprintf(fp, fmt, args);
	va_end(args);
}
